package ru.housewife.service.wares;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.WaresGroupForm;
import ru.housewife.model.WaresGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class GetWaresGroupsTree implements HibernateAction<List<WaresGroupForm>> {

    @Override
    public List<WaresGroupForm> execute(Session session) {
        return execute(session, null);
    }

    public List<WaresGroupForm> execute(Session session, WaresGroupForm parentFrm) {
        Query q;
        if (parentFrm != null) {
            q = session.createQuery("select wg from WaresGroup wg where wg.parent.id=:wareGroupId");
            q.setLong("wareGroupId", parentFrm.getId());
        } else {
            q = session.createQuery("select wg from WaresGroup wg where wg.parent.id is NULL");
        }
        List<WaresGroup> lst = q.list();
        List<WaresGroupForm> result = new ArrayList<WaresGroupForm>(lst.size());
        for (WaresGroup wg : lst) {
            WaresGroupForm frm = createWaresGroupForm(wg, parentFrm);
            frm.setChilds(execute(session, frm));
            result.add(frm);
        }
        return result;
    }

    private WaresGroupForm createWaresGroupForm(WaresGroup wg, WaresGroupForm parentFrm) {
        WaresGroupForm frm = new WaresGroupForm();
        frm.setId(wg.getId());
        frm.setName(wg.getName());
        frm.setDefaultGroup(wg.isDefaultGroup());
        frm.setOrder(wg.getOrder());
        frm.setParent(parentFrm);
        return frm;
    }
}
